//
//  VideoDetailController.m
//  coba-iOS
//
//  Created by 郭四虎 on 15/12/22.
//  Copyright © 2015年 YouKu. All rights reserved.
//

#import "VideoDetailController.h"
#import <MediaPlayer/MediaPlayer.h>
#import <WebKit/WebKit.h>
#import "AppDelegate.h"

#define BTNHEIGHT GDTMOB_AD_SUGGEST_SIZE_320x50.height
@interface VideoDetailController ()<WKNavigationDelegate,UIWebViewDelegate,WKScriptMessageHandler,GDTMobBannerViewDelegate>
{
    UIDeviceOrientation orientation;
    BOOL isHandBack;
}
@property (strong, nonatomic) WKWebView *web;
//@property (weak, nonatomic) IBOutlet UIWebView *web;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UILabel *titleLb;
@property (weak, nonatomic) IBOutlet UILabel *contentLb;
@property (strong, nonatomic) IBOutlet UIImageView *adBtn;
@property (strong, nonatomic) GDTMobBannerView *bannerView;

@end

@implementation VideoDetailController
- (GDTMobBannerView *)bannerView
{
    if (!_bannerView) {
        _bannerView = [[GDTMobBannerView alloc] initWithFrame:CGRectMake(0, 0,
                                                                         GDTMOB_AD_SUGGEST_SIZE_320x50.width*SCALEX,
                                                                         GDTMOB_AD_SUGGEST_SIZE_320x50.height) appkey:GGTID placementId:@"8030610115788238"];
        
        // 设置广告视图的位置 宽与高设置为0即可 该广告视图默认是横竖屏自适应 但需要在旋转时调用orientationChanged 方法
        // Set the frame of advertisement view
        _bannerView.delegate = self;
        _bannerView.currentViewController = self; //设置当前的ViewController
        _bannerView.interval = 30; //【可选】设置刷新频率;默认30秒
        _bannerView.isGpsOn = NO; //【可选】开启GPS定位;默认关闭
        _bannerView.showCloseBtn = YES; //【可选】展示关闭按钮;默认显示
        _bannerView.isAnimationOn = YES; //【可选】开启banner轮播和展现时的动画效果;默认开启
        
        [_bannerView loadAdAndShow];
    }
    return _bannerView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    WKWebViewConfiguration *con = [[WKWebViewConfiguration alloc]init];
//    NSString * GetImages = [NSString stringWithFormat:
//                            @"alert(\"WKUserScript注入js\");"];
//    WKUserScript *script = [[WKUserScript alloc]initWithSource:GetImages injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
//    [con.userContentController addScriptMessageHandler:self name:@"myApp"];
//    [con.userContentController addUserScript:script];
    con.allowsInlineMediaPlayback = YES;
    self.web = [[WKWebView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, 233*SCALEY)configuration:con];
    [self.view addSubview:self.web];
    self.web.navigationDelegate = self;
    
    self.web.scrollView.scrollEnabled = NO;
    self.title = @"视频详情";
    
    if (IPHONE6P) {
        //[self updateFrame:50];
        self.contentLb.font = [UIFont systemFontOfSize:18];
    }else if (IPHONE6){
        //[self updateFrame:30];
        self.contentLb.font = [UIFont systemFontOfSize:16];
    }else{
        
    }
    
    //_web.allowsInlineMediaPlayback = YES;
    //_web.mediaPlaybackRequiresUserAction = YES;
    [self initUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fullScreen:) name: UIWindowDidBecomeVisibleNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notFullScreen:) name:UIWindowDidBecomeHiddenNotification object:nil];
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
    
}
//#define DMPUBLISHERID        @"56OJyM1ouMGoULfJaL"
//#define DMPLCAEMENTID_BANNER @"16TLwebvAchkANUH_krQ7vOz"


- (void)orientChange:(NSNotification*)no
{
    NSDictionary *dic = no.userInfo;
    
    NSLog(@"%@",dic);
    
    UIDeviceOrientation  orient = [UIDevice currentDevice].orientation;
    /*
     UIDeviceOrientationUnknown,
     UIDeviceOrientationPortrait,            // Device oriented vertically, home button on the bottom
     UIDeviceOrientationPortraitUpsideDown,  // Device oriented vertically, home button on the top
     UIDeviceOrientationLandscapeLeft,       // Device oriented horizontally, home button on the right
     UIDeviceOrientationLandscapeRight,      // Device oriented horizontally, home button on the left
     UIDeviceOrientationFaceUp,              // Device oriented flat, face up
     UIDeviceOrientationFaceDown             // Device oriented flat, face down   */
    
    NSLog(@"%ld",(long)orient);
    
    switch (orient)
    {
        case UIDeviceOrientationPortrait:
            
            //[[UIDevice currentDevice] setValue:[NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft] forKey:@"orientation"];
            break;
        case UIDeviceOrientationLandscapeLeft:
            
            
            break;
        case UIDeviceOrientationPortraitUpsideDown:
            
            //[[UIDevice currentDevice] setValue:[NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight] forKey:@"orientation"];
            break;
        case UIDeviceOrientationLandscapeRight:
            
            
            break;
            
        default:
            break;
    }
    orientation = orient;
}

-(void)fullScreen:(NSNotification *)notification{
    
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.isFull = YES;
    NSLog(@"全屏");
    
//    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
//    orientation = UIDeviceOrientationLandscapeRight;
//    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
}

- (void)notFullScreen:(NSNotification *)noti
{
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.isFull = NO;
    
    NSLog(@"退出去评");
}

- (BOOL)shouldAutorotate
{
    return YES;
}

//- (UIInterfaceOrientationMask)supportedInterfaceOrientations
//{
//    return UIInterfaceOrientationMaskLandscapeLeft;
//}

- (void)updateFrame:(CGFloat)value
{
    CGRect rect = _web.frame;
    rect.size.height +=value;
    _web.frame = rect;
    
    CGRect re1 = _scrollView.frame;
    re1.origin.y +=value;
    re1.size.height -= value;
    _scrollView.frame = re1;
}

- (void)initUI
{
    self.titleLb.text = _model.title;
    
    //NSString *str = [NSString stringWithFormat:@"%@%@",CAR_URL,_model.video_page_url];
    NSString *str = _model.video_page_url;
    
    [self.web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    
//自适应
    
    self.contentLb.text = [NSString stringWithFormat:@"        %@",_model.content];

    CGSize size = [self.contentLb.text boundingRectWithSize:CGSizeMake(WIDTH, MAXFLOAT) options:(NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)attributes:@{NSFontAttributeName:self.contentLb.font} context:nil].size;
    
    CGRect rect = self.contentLb.frame;
    rect.size.height = size.height;
    self.contentLb.frame = rect;
    
    CGRect scrollrect = _scrollView.frame;
    CGSize scrollsize;

//    _adBtn = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"meitu_1.jpg"]];
    
    if ((rect.origin.y + rect.size.height +10)> (scrollrect.size.height*SCALEY - BTNHEIGHT)) {
        
        self.scrollView.contentSize = CGSizeMake(WIDTH, rect.origin.y + rect.size.height +10+BTNHEIGHT);
        
        scrollsize = _scrollView.contentSize;
        
        self.bannerView.frame = CGRectMake(0, scrollsize.height - BTNHEIGHT, WIDTH, BTNHEIGHT);
        
    }else{
        
        self.bannerView.frame = CGRectMake(0, scrollrect.size.height*SCALEY - BTNHEIGHT+1, WIDTH, BTNHEIGHT);
    }
//    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//    btn.frame = CGRectMake(10, 200, 100, 30);
//    btn.backgroundColor = [UIColor blackColor];
//    [btn addTarget:self action:@selector(showAD) forControlEvents:UIControlEventTouchUpInside];
//    [_scrollView addSubview:btn];
    
    [_scrollView addSubview:self.bannerView];
}
- (void)showAD
{
    //[_feedAdView present];
}
//- (void)webViewDidFinishLoad:(UIWebView *)webView
//{
//    [self.web Hidden];
//    
//}
//- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error
//{
//    NSLog(@"%@",error);
//    [self.web Message:@"请检查网络"];
//}
//
//- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
//{
//    NSString *str = [[request URL]absoluteString];
//    
//    NSLog(@"%@",str);
//    return YES;
//}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    NSLog(@"aaa");
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    
    NSLog(@"%@",navigationResponse.response.URL.absoluteString);
    decisionHandler(WKNavigationResponsePolicyAllow);
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation
{
    NSLog(@"start");
    if (![ISBUS boolValue]) {
        [self.web Loading_0000];
    }
    [self.web performSelector:@selector(Hidden) withObject:nil afterDelay:5];
}
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation
{
    NSLog(@"commit");
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"fail");
    [self.web Message:@"请检查网络" HiddenAfterDelay:1];
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
//    NSString * GetImages = [NSString stringWithFormat:
//                            
//                            @"function Images(){\
//                            var objs = document.getElementsByTagName(\"div\");\
//                            for(var i=0;i<objs.length;i++){\
//                            objs[i].onclick = function () {\
//                            document.location=\"myweb:imageClick:\"+this.id;\
//                            };\
//                            };\
//                            \
//                            };"];
//    [self.web evaluateJavaScript:GetImages completionHandler:^(id _Nullable aa, NSError * _Nullable error) {
//        
//        NSLog(@"aaaaa");
//    }];
//    [self.web evaluateJavaScript:@"Images()" completionHandler:^(id _Nullable qq, NSError * _Nullable error) {
//        
//        NSLog(@"qqqq");
//    }];
    
    NSLog(@"finish");
    [self.web Hidden];
}

- (void)backFront
{
    isHandBack = YES;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    if (isHandBack) {
        [self.web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];
    }
    
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIWindowDidBecomeVisibleNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIWindowDidBecomeHiddenNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
    
    
}

- (void)bannerViewMemoryWarning
{
    NSLog(@"%s",__FUNCTION__);
}

// 请求广告条数据成功后调用
//
// 详解:当接收服务器返回的广告数据成功后调用该函数
- (void)bannerViewDidReceived
{
    NSLog(@"%s",__FUNCTION__);
}

// 请求广告条数据失败后调用
//
// 详解:当接收服务器返回的广告数据失败后调用该函数
- (void)bannerViewFailToReceived:(NSError *)error
{
    NSLog(@"%s, Error:%@",__FUNCTION__,error);
}

// 应用进入后台时调用
//
// 详解:当点击下载或者地图类型广告时，会调用系统程序打开，
// 应用将被自动切换到后台
- (void)bannerViewWillLeaveApplication
{
    NSLog(@"%s",__FUNCTION__);
}

// banner条曝光回调
//
// 详解:banner条曝光时回调该方法
- (void)bannerViewWillExposure
{
    NSLog(@"%@%s",self.title,__FUNCTION__);
}

// banner条点击回调
//
// 详解:banner条被点击时回调该方法
- (void)bannerViewClicked
{
    
    NSLog(@"%s",__FUNCTION__);
}
- (void)bannerViewWillPresentFullScreenModal
{

    NSLog(@"%s",__FUNCTION__);
}
/**
 *  banner条被用户关闭时调用
 *  详解:当打开showCloseBtn开关时，用户有可能点击关闭按钮从而把广告条关闭
 */
- (void)bannerViewWillClose
{
    NSLog(@"%s",__FUNCTION__);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
